const express = require('express');
const axios = require('axios');
const cheerio = require('cheerio');
const cors = require('cors');

const app = express();
app.use(cors());

app.get('/api/articles', async (req, res) => {
    try {
        const websiteURL = 'http://www.mathorcup.org/prize';
        const { data } = await axios.get(websiteURL);
        const $ = cheerio.load(data);

        const articles = [];

        $('.tz_cont ul li').each((index, element) => {
            const title = $(element).find('p a').text().trim();
            const link = $(element).find('p a').attr('href');
            articles.push({ title, link });
        });

        res.json({ articles });
    } catch (error) {
        console.error(error);
        res.status(500).send('Server error');
    }
});

app.listen(5002, () => {
    console.log('Server is running on port 5002');
});